#include <ToolBox/gl/vbo.h>

Vbo::Vbo()
{
    InitBuffers();
}

void Vbo::InitBuffers()
{
    glGenBuffers(1,&vertexBuffer);
    glGenBuffers(1,&colorBuffer);
    glGenBuffers(1,&indexBuffer);
    glGenBuffers(1,&pickingBuffer);
    glGenBuffers(1,&normalBuffer);
}

int Vbo::SetVertex(int indiceVertex, Vectorf coordinate)
{
    /*! Dans un premier temps, on définit le buffer courant : le buffer de sommets */

    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);

    /*!	Ensuite, on transforme le Vector en tableau de floats à l'aide de la méthode ToArray(); */

    float * arg = coordinate.Array();

    /*! La méthode glMapBuffer permet de récupérer dans un tableau les données du buffer courant */

    float * vertices = (float *) glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE);

    for(int i=0;i<dimensionVertex;i++)
    {
        vertices[(indiceVertex*dimensionVertex)+i]=arg[i];
    }

    glUnmapBuffer(GL_ARRAY_BUFFER);
}

Vectorf Vbo::GetVertex(int indiceVertex)
{
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);

    Vectorf vectorTemp;

    float * vertices = (float *) glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);

    if(dimensionVertex==1)
    {
        vectorTemp.x(vertices[dimensionVertex*indiceVertex]);
    }
    else if (dimensionVertex==2)
    {
        vectorTemp.x(vertices[indiceVertex*dimensionVertex]);
        vectorTemp.y(vertices[(indiceVertex*dimensionVertex)+1]);
    }
    else if (dimensionVertex==3)
    {
        vectorTemp.x(vertices[indiceVertex*dimensionVertex]);
        vectorTemp.y(vertices[(indiceVertex*dimensionVertex)+1]);
        vectorTemp.z(vertices[(indiceVertex*dimensionVertex)+2]);
    }

    glUnmapBuffer(GL_ARRAY_BUFFER);

    return vectorTemp;
}

std::vector<Vectorf *> Vbo::GetVertex()
{
    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);

    Vectorf * vectorTemp;
    std::vector<Vectorf * > vectors;

    float * vertices = (float *) glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY);

    for(int i=0;i<size;i+=3)
    {

        vectorTemp= new Vectorf(0.0,0.0,0.0);

        vectorTemp->x(vertices[i]);
        vectorTemp->y(vertices[(i)+1]);
        vectorTemp->z(vertices[(i)+2]);

        vectors.push_back(vectorTemp);
    }
    glUnmapBuffer(GL_ARRAY_BUFFER);

    return vectors;
}
